﻿using SqlSugar;
using Qy.Core;
using System.Threading.Tasks;

namespace Qy.Scenario;

[AppService]
public class DocPostMarkService : QyRepository<DocPostMark>
{
    public DocPostMarkService(ApplicationContext applicationContext) : base(applicationContext) { }

    public async Task<ViewDocPostMark> GetOne(int aid)
    {
        //Sql sql = Sql.Builder;
        //sql.Select("docuser.Nickname,user.Nickname as MarkName,docpost.Title,docpost.Time InsertTime,mark.*")
        //     .From(DbTableName.OasDocPostMark + " as mark")
        //     .LeftJoin(DbTableName.QyAdminUser + " as user").On("mark.Uid=user.Id");
        //sql.LeftJoin(DbTableName.OasDocPost + " as docpost").On("docpost.Id=mark.Aid");
        //sql.LeftJoin(DbTableName.QyAdminUser + " as docuser").On("docuser.Id=docpost.Uid");
        //sql.Where("mark.Aid =@0", aid);
        //return await CreateDAO().FirstOrDefaultAsync<ViewDocPostMark>(sql);

        return await Queryable()
                   .LeftJoin<DocPost>((data, post) => data.Aid == post.Id)
                   .LeftJoin<User>((data,post, user) => data.Uid == user.Id)
                   .LeftJoin<User>((data,post, user,docUser) => post.Uid == docUser.Id)
                   .Select((data, post,user,docUser) => new ViewDocPostMark()
                   {
                       NickName = docUser.NickName,
                       MarkName = user.NickName,
                       Title = post.Title,
                       InsertTime = post.Time,
                       Id  = data.Id.SelectAll(),
                   })
                   .FirstAsync(data => data.Aid == aid);
    }

    public async Task<ViewDocPostMark> GetOneAsync(int aid)
    {
        ViewDocPostMark artMark = await GetOne(aid);
        if (artMark != null) return artMark;

        //Sql sql = Sql.Builder;
        //sql.Select("docpost.*,user.Nickname")
        //    .From(DbTableName.OasDocPost + " as docpost")
        //    .LeftJoin(DbTableName.QyAdminUser + " user").On("docpost.Uid=user.Id");
        //sql.Where("docpost.Id =@0", aid);
        //ViewDocPostAndCate doc = await CreateDAO().FirstOrDefaultAsync<ViewDocPostAndCate>(sql);

        ViewDocPostAndCate doc = await Context.Queryable<DocPost>()
                       .LeftJoin<User>((data, user) => data.Uid == user.Id)
                       .Select((data, user) => new ViewDocPostAndCate()
                       {
                           Id = data.Id.SelectAll(),
                           NickName = user.NickName,
                       }, true)
                       .FirstAsync(data => data.Id == aid);

        ViewDocPostMark am = new()
        {
            Title = doc.Title,
            Aid = doc.Id,
            NickName = doc.NickName,
            InsertTime = doc.Time
        };
        return am;

    }
}
